package com.ruoyi.session.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.strategy.domain.Strategy;
import com.ruoyi.strategy.mapper.StrategyMapper;
import com.ruoyi.session.domain.Session;
import com.ruoyi.session.domain.SessionVo;
import com.ruoyi.detail.mapper.SessionDetailMapper;
import com.ruoyi.session.mapper.SessionMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.session.service.ISessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @program: RuoYi-Vue-master
 * @description:
 * @author: xgw
 * @create: 2025-01-06 20:48
 **/


@Service
public class SessionServiceImpl implements ISessionService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private StrategyMapper strategyMapper;

    @Autowired
    private SessionMapper sessionMapper;

    @Autowired
    private SessionDetailMapper sessionDetailMapper;


    /**
     * 查询出所有的需要展示的数据，session.id  session.title  strategy.id  strategy.name  user.id  user.name
     * @return
     */
    @Override
    public AjaxResult selectExistSession() {
       return selectCommon(sessionMapper.selectExistSession());
    }
    /**
    * @Description: 插入会话
    * @Param: [session]
    * @return: com.ruoyi.common.core.domain.AjaxResult
    * @Author: xgw
    * @Date: 2025/1/7
    */
    @Override
    public AjaxResult insertSession(Session session) {
        //判断该用户，是否存在过该会话，即userId ，title 相同，又分为is_deleted = 0/1
        //is_deleted = 0 直接更新标题，更改is_deleted = 1
        Session sessions = sessionMapper.selectSessionByUserIdAndTitle(session.getUserId(), session.getTitle());
        System.out.println(sessions);
        if(Objects.isNull(sessions)){
            sessionMapper.insertSession(session);
            return AjaxResult.success("插入成功！！",session);
        }
        if(0==sessions.getIsDeleted()){
            sessions.setStrategyId(session.getStrategyId());
            sessions.setIsDeleted(1);
            sessions.setTimestamp(LocalDateTime.now());
            return  AjaxResult.success("插入成功！！",session);
        }
        //is_deleted = 1 则当前session已经存在
        if (1==sessions.getIsDeleted()){
            AjaxResult.error("插入失败，当前会话已经存在，请更改标题！！",session);
        }

        return AjaxResult.success("插入成功！！",session);
    }

    /**
     * 根据session_id删除会话
     * @param sessionId
     * @return
     */
    @Override
    public AjaxResult deleteSessionBySessionId(Integer sessionId) {
        //删除session
        int flag = sessionMapper.deleteSessionById(sessionId);
        //删除session相关的session_detail
        sessionDetailMapper.deleteSessionDetailBySessionId(sessionId);
        return AjaxResult.success("删除成功");
    }

    /**
    * @Description: 动态查询  username（模糊） strategyId（策略id） title（标题）
    * @Param: [username, strategyId, title]
    * @return: com.ruoyi.common.core.domain.AjaxResult
    * @Author: xgw
    * @Date: 2025/1/7
    */
    @Override
    public AjaxResult dynamicSelectSession(String username, Integer strategyId, String title) {
        //查询出符合的动态数据
        List<Session> sessions = sessionMapper.dynamicSelectSession(username, strategyId, title);
        //包装成sessionVo
        return selectCommon(sessions);
    }

    @Override
    public AjaxResult selectHistorySession(Integer userId) {
        return AjaxResult.success("查询成功",sessionMapper.selectSessionByUserId(userId));
    }

    public AjaxResult selectSessionBySearch(String title , Integer userId) {
        //1.查询出会话标题符合的会话
        sessionMapper.selectSessionBySearch(title,userId);
        return selectCommon(sessionMapper.selectSessionBySearch(title,userId));
    }

    @Override
    public int updateSessionById(Integer sessionId, String title) {
        sessionMapper.updateSessionById(sessionId,title);
        return 0;
    }

    //查询全部和动态查询的公共方法
    public AjaxResult selectCommon(List<Session> sessions){
        //1.根据session查询出对应的user，strategy
        List<SessionVo> svList = new LinkedList<>();
        for (Session session : sessions) {
            Integer userId = session.getUserId();
            //Integer包装类转化为Long包装类
            System.out.println("----------------");
            System.out.println(userId);
            Long aLong = userId.longValue();
            SysUser sysUser = sysUserMapper.selectUserById(aLong);
            Strategy strategy = strategyMapper.selectStrategyById(session.getStrategyId());
            svList.add(new SessionVo(session.getId(),userId,strategy.getId().intValue()
                    ,session.getTitle(),sysUser.getUserName(),strategy.getName()));
        }
        return AjaxResult.success("查询成功",svList);
    }

}
